<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t('人员花名册') }}</span>
    </div>
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('姓名')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="$t('姓名')"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <el-form-item :label="$t('归属部门')" prop="deptId">
        <tree-select v-model="queryParams.deptId" node-key="id" :default-expand-all="true" :data="dict.deptOptions" :placeholder="$t('请选择')" clearable>
          <label slot="option-label" slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }" :class="labelClassName">
            {{ $t(node.label) }}
            <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
          </label>
        </tree-select>
      </el-form-item>
      <el-form-item :label="$t('状态')" prop="status">
        <el-select v-model="queryParams.status" size="small" clearable :placeholder="$t('请选择')">
          <el-option
            v-for="dict in dict.entryStatus"
            :key="dict.dictValue"
            :label="$t(dict.dictLabel)"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t('搜索') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="hrBaseList" border>
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('姓名')" align="center" prop="name">
        <template slot-scope="scope">
          <router-link
            target="_blank"
            :to="{path:'/oa/hr/base/hrBaseHome',query:{hrId:scope.row.id,menuPath: menuKey}}"
            class="link_a"
          >{{ scope.row.name }}</router-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('关联账号')" align="center" prop="userName" />
      <el-table-column :label="$t('出生年月')" align="center" prop="birthDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birthDate, '{y}-{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('部门')" align="center" prop="deptName" />
      <!--      <el-table-column :label="$t('状态')" align="center" prop="status">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ getDictVaule('entryStatus', scope.row.status) }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="80">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            icon="el-icon-aim"
            @click="selectHr(scope.row)"
          >{{ $t('选择') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改人员花名册对话框 -->
    <el-dialog
      :title="$t(title)"
      :visible.sync="formOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      custom-class="dialogForm"
      append-to-body
    >
      <hrBaseForm ref="hrBaseForm" />
    </el-dialog>

    <!-- 导入 -->
    <el-dialog :title="$t('人员花名册导入')" :visible.sync="upload.open" width="400px" :close-on-click-modal="false" :lock-scroll="false">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          {{ $t('将文件拖到此处，或') }}
          <em>{{ $t('上传') }}</em>
        </div>
        <!--        <div slot="tip" class="el-upload__tip">-->
        <!--          <el-checkbox v-model="upload.updateSupport" /> {{ $t('是否更新已经存在的数据') }}-->
        <!--        </div>-->
        <div slot="tip" class="el-upload__tip" style="color:red">
          {{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}
          <el-link type="primary" style="font-size:12px" @click="fetchTemplate">
            {{ $t('下载模板') }}
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="upload.open = false">{{ $t("取消") }}</el-button>
        <el-button type="primary" @click="submitFileForm">{{ $t("确定") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHrBase, delHrBase } from '@/api/oa/hr/hrBase'
import hrBaseForm from './hrBaseForm.vue'
import { listPost } from '@/api/system/post'
import { treeselect } from '@/api/system/dept'
import TreeSelect from '@/components/TreeSelect/index'
import { getToken } from '@/utils/auth'

export default {
  components: {
    hrBaseForm,
    TreeSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 人员花名册表格数据
      hrBaseList: [],
      // 部门树选项
      deptOptions: undefined,
      // 弹出层标题
      title: '人员花名册',
      // 是否显示弹出层
      formOpen: false,
      // 查询参数
      queryParams: {
        name: undefined,
        status: 'zz',
        sex: undefined,
        birthDate: undefined,
        idType: undefined,
        idNum: undefined,
        age: undefined,
        nation: undefined,
        deptId: undefined,
        politicalOutlook: undefined,
        position: undefined,
        entryTime: undefined,
        censusRegisterType: undefined,
        censusRegisterAddress: undefined,
        currentAddress: undefined,
        contractType: undefined,
        international: undefined,
        workplaceType: undefined,
        marriage: undefined,
        email: undefined,
        phone: undefined,
        takeEffectTime: undefined,
        terminationTime: undefined,
        contractTerm: undefined,
        renewalTime: undefined,
        positiveTime: undefined,
        goodAtField: undefined,
        investmentPhilosophy: undefined,
        staffType: undefined,
        workingYear: undefined,
        isSel: 'Y',
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      dict: {
        // 性别
        sysUserSexs: [],
        // 证件类型
        hrIdTypes: [],
        // 政治面貌
        hrPoliticalOutlook: [],
        // 职位
        hrPositions: [],
        // 户籍类型
        hrCensusRegisterTypes: [],
        // 合同或协议类型
        hrContractTypes: [],
        // 国籍
        hrInternationals: [],
        // 职场类型
        hrWorkplaceTypes: [],
        // 婚姻状况
        marriages: [],
        // 员工类型
        hrStaffTypes: [],
        // 状态
        entryStatus: [],
        deptOptions: undefined
      },
      menuKey: '',
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/hrBase/hrBase/importData'
      }
    }
  },
  watch: {
    '$route': {
      handler(val) {
        this.menuKey = val.query.menuKey
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.initDict()
    this.getList()
  },
  methods: {
    /** 查询人员花名册列表 */
    getList() {
      this.loading = true
      listHrBase(this.queryParams).then(response => {
        this.hrBaseList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        name: undefined,
        sex: undefined,
        birthDate: undefined,
        idType: undefined,
        idNum: undefined,
        age: undefined,
        nation: undefined,
        deptId: undefined,
        politicalOutlook: undefined,
        position: undefined,
        entryTime: undefined,
        censusRegisterType: undefined,
        censusRegisterAddress: undefined,
        currentAddress: undefined,
        contractType: undefined,
        international: undefined,
        workplaceType: undefined,
        marriage: undefined,
        email: undefined,
        phone: undefined,
        takeEffectTime: undefined,
        terminationTime: undefined,
        contractTerm: undefined,
        renewalTime: undefined,
        positiveTime: undefined,
        goodAtField: undefined,
        investmentPhilosophy: undefined,
        staffType: undefined,
        workingYear: undefined
      }
      this.resetForm('form')
    },
    // 搜索按钮操作
    queryHandle() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.status = undefined
      this.queryHandle()
    },
    // 新增按钮操作
    addHandle() {
      this.formOpen = true
      this.$nextTick(() => {
        this.$refs.hrBaseForm.init(null)
      })
    },
    // 修改按钮操作
    updateHandle(row) {
      this.formOpen = true
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        this.$refs.hrBaseForm.init(row)
      })
    },
    // 删除按钮操作
    deleteHandle(row) {
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delHrBase(row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {
      })
    },
    selectHr(row) {
      // 关闭当前页面
      // 判断数据是否关联
      if (row.userId !== null && row.userId !== undefined && row.userId !== '') {
        return this.msgError(this.$t('此用户已经关联'))
      }
      this.$parent.$parent.form.hrId = row.id
      this.$parent.$parent.form.nickName = row.name
      this.$parent.$parent.openHr = false
    },
    initDict() {
      // 性别
      this.getDicts('sys_user_sex').then(response => {
        this.dict.sysUserSexs = response.data
      })
      // 证件类型
      this.getDicts('hr_id_type').then(response => {
        this.dict.hrIdTypes = response.data
      })
      // 政治面貌
      this.getDicts('hr_political_outlook').then(response => {
        this.dict.hrPoliticalOutlook = response.data
      })
      // 职位
      listPost({}).then(response => {
        this.dict.hrPositions = response.rows
      })
      // this.getDicts('hr_position').then(response => {
      //   this.dict.hrPositions = response.data
      // })
      // 户籍类型
      this.getDicts('hr_census_register_type').then(response => {
        this.dict.hrCensusRegisterTypes = response.data
      })
      // 合同或协议类型
      this.getDicts('hr_contract_type').then(response => {
        this.dict.hrContractTypes = response.data
      })
      // 国籍
      this.getDicts('hr_international').then(response => {
        this.dict.hrInternationals = response.data
      })
      // 职场类型
      this.getDicts('hr_workplace_type').then(response => {
        this.dict.hrWorkplaceTypes = response.data
      })
      // 婚姻状况
      this.getDicts('marriage').then(response => {
        this.dict.marriages = response.data
      })
      // 员工类型
      this.getDicts('hr_staff_type').then(response => {
        this.dict.hrStaffTypes = response.data
      })
      this.getDicts('hr_entry_status').then(response => {
        this.dict.entryStatus = response.data
      })
      treeselect().then(response => {
        this.dict.deptOptions = response.data
      })
    },
    getDictVaule(listName, key) {
      const list = this.dict[listName]
      for (let i = 0; i < list.length; i++) {
        const dict = list[i]
        if (dict.dictValue === key) {
          return dict.dictLabel
        }
      }
    },
    handleImport() {
      this.upload.title = this.$t('导入')
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 下载模板
    fetchTemplate() {
      var href1 = window.location.href
      var href2 = this.$route.path
      var url = href1.substring(0, href1.indexOf(href2))
      window.location.href = url + '/template/registerRollImportTemplate.xlsx'
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
}
</script>
